/*
 * Useful Javascript Tools
 * By Olivier St-Laurent
 *
 */

function escapePost(str) {
    if (str) {
        str += '';
        str = str.replace(/%/gm, '%25');
        str = str.replace(/\+/gm, '%2B');
        str = str.replace(/&/gm, '%26');
        str = str.replace(/=/gm, '%3D');
        str = str.replace(/ /gm, '%20');
        str = str.replace(/\t/gm, '%09');
        str = str.replace(/\r\n/gm, '%0D');
        str = str.replace(/\r/gm, '%0D');
        str = str.replace(/\n/gm, '%0D');
    }
    return str;
}

function formValuesToArray(formname) {
    var formData = new Object();
    var elems = (document.forms[formname] || $(formname)[0]).elements;
    for (var i = 0; i < elems.length; i++) {
        if (
            (elems[i].type != 'radio' && elems[i].type != 'checkbox')
            || (
                (elems[i].type == 'radio' || elems[i].type == 'checkbox')
                && elems[i].checked == true
                )
            ) {
            if (elems[i].name.match(/\[\]$/g)) {
                //If multiple inputs are named with empty bracket (name="elem[]"), they will be put in an array for themselves
                var nameNoBracket = elems[i].name.replace('[]', '');
                if (typeof formData[nameNoBracket] === "undefined" || !(formData[nameNoBracket] instanceof Array)) {
                    formData[nameNoBracket] = new Array();
                }
                formData[nameNoBracket].push(elems[i].value);
            } else {
                formData[elems[i].name] = elems[i].value;
            }
        }
    }
    return formData;
}

function formValuesToString(formname) {
    var elems = "";
    var elem = (document.forms[formname] || $(formname)[0]).elements;
    for (var i = 0; i < elem.length; i++) {
        if ((elem[i].type != 'radio' && elem[i].type != 'checkbox') || ((elem[i].type == 'radio' || elem[i].type
            == 'checkbox') && elem[i].checked == true)) {
            elems += ((elems == "") ? "" : "&") + escapePost(elem[i].name) + "=" + escapePost(elem[i].value);
        }
    }
    return elems;
}
